define([
	"UtilDir/util",
	"UtilDir/tool",
    "UtilDir/org/selectOrg",
    "UtilDir/searchBlock",
	"http://api.tianditu.gov.cn/api?v=4.0&tk=aeb17a8215786a5dd17f5f9c92bebc0c",
	"Date","DateCN", "css!DateCss",
	"EasyUI","EasyUI-lang"
    ],function(Util, Tool, SelectOrg, SearchBlock){

    var map = null;

	var getQhDrillOverviewController = function(){
		return getServer() + "/qh/qhDrillOverviews";
	};
	var getQhDrillHistogramController = function(){
		return getServer() + "/qh/qhDrillHistograms";
	};
	/**
	 * 页面初始化
	 */
	var init = function(){
        initSearchBlock();
        queryBtnBind();
        initcreateProvince();
        // setTimeout(function () {
        //     // initMap();
        //
        // },1000)
		initMap();
	};
    var initcreateProvince = function () {
        var html = "";
        $("#citySelect").append(html);
        $("#areaSelect").append(html);
        $.ajax({
            url: "/divisions/root/subdivisions",
            contentType: "application/json",
            type: "get",
            success: function (data) {
                $.each(data, function (idx, item) {
                    html += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
                });
                $("#provinceSelect").append(html);
            }
        });
        $("#provinceSelect").change(function () {
            var html = '<option value="" disabled selected style="display:none;">请选择</option>';
            $("#citySelect option").remove();
            $("#citySelect").append(html);
            $("#areaSelect option").remove();
            $("#areaSelect").append(html);
            var divisionId = $(this).find("option:selected").attr("exid");
            if ($(this).val() == "北京市" || $(this).val() == "天津市" || $(this).val() == "上海市" || $(this).val() == "重庆市") {
                $("#citySelect").append("<option value='" + $(this).val() + "' exid='" + divisionId + "'>" + $(this).val() + "</option>");
                return;
            }
            $.ajax({
                url: "/divisions/" + divisionId + "/subdivisions",
                contentType: "application/json",
                type: "get",
                success: function (data) {
                    $.each(data, function (idx, item) {
                        html += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
                    });
                    $("#citySelect").append(html);
                }
            });
        });
        $("#citySelect").change(function () {
            if ($(this).val() == "") return;
            var html = '<option value="" disabled selected style="display:none;">请选择</option>';
            $("#areaSelect option").remove();
            $("#areaSelect").append(html);
            var divisionId = $(this).find("option:selected").attr("exid");
            $.ajax({
                url: "/divisions/" + divisionId + "/subdivisions",
                contentType: "application/json",
                type: "get",
                success: function (data) {
                    $.each(data, function (idx, item) {
                        html += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
                    });
                    $("#areaSelect").append(html);
                }
            });
        });
    }
	var initSearchBlock = function(){
        SearchBlock.init("searchBlock");
        // $("#checkDataType").change(function () {
        //     if ($(this).val() == "钻孔综合柱状图数据"){
        //     	createQhDrillHistogramGrid();
        //     }else{
        //     	createQhDrillOverviewGrid();
        //     }
        //
        // });
	};
	var queryBtnBind = function(){
        $("#btnSearch").click(function () {
            map.clearOverLays();
            showDrillOverviewData();
        });

        $("#btnReset").click(function () {
            map.clearOverLays();
            $("#provinceSelect").val("");
            $("#citySelect").val("");
            $("#areaSelect").val("");
            $("#town").val("");
            $("#siteClass").val("");
        });
	};

	var getQhDrillOverview = function(id){
		$.ajax({
			url: getQhDrillOverviewController() + "/"+id,
			type: "get",
			success: function (data) {
				editProvince(data.province, data.city, data.area);
				Tool.deserialize("qhDrillOverviewForm", data);
			}
		});
	};
	var getQhDrillHistogram = function(id){
		$.ajax({
			url: getQhDrillHistogramController() + "/"+id,
			type: "get",
			success: function (data) {
				editProvince(data.province, data.city, data.area);
				viewFileUpload(data.attachment);
				Tool.deserialize("qhDrillHistogramForm", data);
			}
		});
	};
    var viewFileUpload = function (fileData) {
        require(['UtilDir/fileupload/multiFileUpload'], function (MFU) {
            var attachIdData = "";
            var attachId = "";
            var fileArray = fileData.split(',');
            if (fileData.length != 0) {
                attachIdData = fileData.split(',');
            }
            var settings = {
                placeAt: "multiFileUpload",
                /*
	            1.0.2版本新增
	            extendColumn:[
	                {name:"文件分类",filed:"category",format:function(file){return file.name}},
	                {name:"备注",filed:"remark",format:function(file){return '机密'}}
	            ],*/
                data: attachIdData,
                onUploadSuccess: function (file) {
                    attachId += file.attachId + ",";
                    if (fileData.length == 0) {
                        $("#attachment").val(attachId.substr(0, attachId.length - 1));
                    } else {
                        $("#attachment").val(fileData + "," + attachId.substr(0, attachId.length - 1));
                    }

                },
                onDeleteSavedFile: function (file) {
                    var index = fileArray.indexOf(file.attachId);
                    fileArray.splice(index, 1);
                    $("#attachment").val(fileArray.toString());
                }
            };
            var MFUpload = MFU.init(settings);

        });
    };
    var editProvince = function (Province, City, Area) {
        debugger;
        var html = "";
        $("#city").append(html);
        $("#area").append(html);
        $.ajax({
            url: "/divisions/root/subdivisions",
            contentType: "application/json",
            type: "get",
            success: function (data) {
                $.each(data, function (idx, item) {
                    if (item.divisionName == Province) {
                        debugger;
                        var divisionId = item.divisionId;
                        var htmlCity = '';
                        if (Province == "北京市" || Province == "天津市" || Province == "上海市" || Province == "重庆市") {
                            $("#city").append("<option value='" + Province + "' exid='" + divisionId + "'>" + Province + "</option>");
                            $('#city').val(City);
                            var htmlArea = '';
                            $.ajax({
                                url: "/divisions/" + divisionId + "/subdivisions",
                                contentType: "application/json",
                                type: "get",
                                success: function (data) {
                                    $.each(data, function (idx, item) {
                                        htmlArea += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
                                    });
                                    $("#area").append(htmlArea);
                                    $('#area').val(Area);
                                }
                            });

                        } else {
                            $.ajax({
                                url: "/divisions/" + divisionId + "/subdivisions",
                                contentType: "application/json",
                                type: "get",
                                success: function (data) {
                                    debugger;
                                    $.each(data, function (idx, item) {
                                        if (item.divisionName == City) {
                                            var divisionId = item.divisionId;
                                            var htmlArea = '';
                                            $.ajax({
                                                url: "/divisions/" + divisionId + "/subdivisions",
                                                contentType: "application/json",
                                                type: "get",
                                                success: function (data) {
                                                    $.each(data, function (idx, item) {
                                                        htmlArea += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
                                                    });
                                                    $("#area").append(htmlArea);
                                                    $('#area').val(Area);
                                                }
                                            });
                                        }
                                        htmlCity += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
                                    });
                                    $("#city").append(htmlCity);
                                    $('#city').val(City);
                                }
                            });
                        }
                    }
                    html += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
                });
                $("#province").append(html);
                $('#province').val(Province);
            }
        });
        $("#province").change(function () {
            var html = '<option value="" disabled selected style="display:none;">请选择</option>';
            $("#city option").remove();
            $("#city").append(html);
            $("#area option").remove();
            $("#area").append(html);
            var divisionId = $(this).find("option:selected").attr("exid");
            if ($(this).val() == "北京市" || $(this).val() == "天津市" || $(this).val() == "上海市" || $(this).val() == "重庆市") {
                $("#city").append("<option value='" + $(this).val() + "' exid='" + divisionId + "'>" + $(this).val() + "</option>");
                return;
            }
            $.ajax({
                url: "/divisions/" + divisionId + "/subdivisions",
                contentType: "application/json",
                type: "get",
                success: function (data) {
                    $.each(data, function (idx, item) {
                        html += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
                    });
                    $("#city").append(html);
                }
            });
        });
        $("#city").change(function () {
            if ($(this).val() == "") return;
            var html = '<option value="" disabled selected style="display:none;">请选择</option>';
            $("#area option").remove();
            $("#area").append(html);
            var divisionId = $(this).find("option:selected").attr("exid");
            $.ajax({
                url: "/divisions/" + divisionId + "/subdivisions",
                contentType: "application/json",
                type: "get",
                success: function (data) {
                    $.each(data, function (idx, item) {
                        html += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
                    });
                    $("#area").append(html);
                }
            });
        });
    }

    var showDrillOverviewData = function () {
        $.ajax({
            url: getQhDrillOverviewController() + "/queryQhDrillOverviewsNoPage",
            contentType:"application/json",
            type: "post",
            data:JSON.stringify({
                province: $("#provinceSelect").val(),
                city: $("#citySelect").val(),
                area: $("#areaSelect").val(),
                town: $("#town").val(),
                siteClass: $("#siteClass").val()
            }),
            success: function (res) {
                var features = res.data;
                if(features.length < 1) {
                    return;
                }
                
                features.forEach(function (feature) {
                    var lon = parseFloat(feature.longitude);
                    var lat = parseFloat(feature.latitude);
                    if(isNaN(lon) || isNaN(lat) || lon > 180 || lon < -180 || lat > 90 || lat < -90) {
                        return;
                    }
                    //创建标注对象
                    var marker = new T.Marker(new T.LngLat(lon, lat));
                    marker.drillCode = feature.drillCode;
                    marker.reportName = feature.reportName;
                    marker.projectName = feature.projectName;
                    marker.siteClass = feature.siteClass;
                    marker.lon = feature.longitude;
                    marker.lat = feature.latitude;
                    marker.id = feature.id;
                    map.addOverLay(marker);
                    marker.addEventListener("click", markerClick);
                })
            },
            pagination: true,
            pageSize: 10
        });
	};

    var markerClick = function (e) {
        var infoWin1 = new T.InfoWindow();
        var sContent =
            //"<div style='margin:0px;width:400px'>" +
            "<table style='border:1px solid #98bf21;padding:3px 7px 2px 7px;border-collapse:collapse'>" +
            "<tr>" +
            "<td>钻孔编号</td>" +
            "<td>" + (this.drillCode || "") + "</td>" +
            "<td>资料报告名称</td>" +
            "<td>" + (this.reportName || "") + "</td>" +
            "</tr>" +
            "<tr>" +
            "<td>勘察工程名称</td>" +
            "<td>" + (this.projectName || "") + "</td>" +
            "<td>场地分类</td>" +
            "<td>" + (this.siteClass || "") + "</td>" +
            "</tr>" +
            "<tr>" +
            "<td>钻孔坐标经度值</td>" +
            "<td>" + (this.lon || "") + "</td>" +
            "<td>钻孔坐标纬度值</td>" +
            "<td>" + (this.lat || "") + "</td>" +
            "</tr>" +
            "<tr>" +
            "<td colspan='2'><a id='drillBtn1' >钻孔概况</a></td>" +
            "<td colspan='2'><a id='drillBtn2'>钻孔综合柱状图</a></td>" +
            "</tr>" +
            "<tr>" +
            "<td colspan='2'><a id='drillBtn3'>标准贯入原位测试结果</a></td>" +
            "<td colspan='2'><a id='drillBtn4'>剪切波速测试结果表</a></td>" +
            "</tr>" +
            "<tr>" +
            "<td colspan='2'><a id='drillBtn5'>土动力测试数据</a></td>" +
            "<td colspan='2'><a id='drillBtn6'>抗震设防参数</a></td>" +
            "</tr>" +
            "</table>";// +
            //"</div>";
        infoWin1.setContent(sContent);
        this.openInfoWindow(infoWin1);

        var drillId = this.drillCode;
        for(var i = 1; i < 7; ++i) {
            (function (i) {
                var buttonName = '#drillBtn' + i;

                $(buttonName).click(function(e){
                    // var type = e.target.id.;
                    toPage(i,drillId);
                });
            })(i);

        }
    };

    var toPage = function(type, id) {
        window.parent.jumpToWithId(type,id);
    };

	var initMap = function() {
        //初始化地图对象
        var config = {
            projection: "EPSG:4326",
            minZoom: 4
        };

        map = new T.Map("mapDiv",config);
        //设置显示地图的中心点和级别
        map.centerAndZoom(new T.LngLat(116.40969,39.89945),5);

        var control=new T.Control.Zoom();
        map.addControl(control);

        //创建比例尺控件对象
        var scale = new T.Control.Scale();
        map.addControl(scale);

        //创建鹰眼控件对象
        var miniMap = new T.Control.OverviewMap({
            isOpen: true,
            size: new T.Point(150, 150)
        });
        map.addControl(miniMap);

        //创建地图类型控件对象
        var ctrl = new T.Control.MapType();
        map.addControl(ctrl);

        var height = window.innerHeight - 150;
        var width = window.innerWidth - 15;

        $("#mapDiv").css("height",height);
        $("#mapDiv").css("width",width);

        map.checkResize();
	};
	return {
		init:init
	};
});
